package com.tuling.netty.client.handler;

import com.tuling.netty.command.Cmd;
import com.tuling.netty.command.CmdHandler;
import com.tuling.netty.command.CmdHandlerMapping;
import com.tuling.netty.listener.NettyListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<Cmd> {
    private NettyListener listener;

    public NettyClientHandler(NettyListener listener) {
        this.listener = listener;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Cmd cmd) throws Exception {
        CmdHandlerMapping handlerMapping = new CmdHandlerMapping();
        CmdHandler cmdHandler = handlerMapping.getHandler(cmd);
        cmdHandler.handle(ctx, cmd);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        IdleState state = event.state();

        switch (state) {
            case WRITER_IDLE:
//                heartbeat(ctx);
                break;
            default:
                super.userEventTriggered(ctx, evt);
        }
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("客户端连接断开...");
        listener.complete(NettyListener.NettyEvent.CONNECTION_CLOSED);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}